<template>
  <wd-toast />
  <wd-form ref="form" :model="model" custom-class="px-4 mt-4">
    <wd-cell-group border>
      <wd-input
        label="用户名"
        label-width="100px"
        prop="username"
        clearable
        v-model="model.username"
        placeholder="请输入用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <wd-input
        label="密码"
        label-width="100px"
        prop="password"
        show-password
        clearable
        v-model="model.password"
        placeholder="请输入密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <view class="flex items-center">
        <wd-input
          label="验证码"
          label-width="100px"
          prop="captcha"
          clearable
          v-model="model.captcha"
          placeholder="请输入验证码"
          :rules="[{ required: true, message: '请填写验证码' }]"
        />
        <image
          class="w-134px h-44px shrink-0"
          @click="refreshCaptcha"
          :src="captchaUrl"
        />
      </view>
    </wd-cell-group>
    <view class="footer mt-4">
      <wd-button type="primary" size="large" @click="handleSubmit" block
        >提交</wd-button
      >
    </view>
    <view class="flex justify-center mt-2">
      没有账号？
      <view class="text-blue" @click="toRegister"> 去注册 </view>
    </view>
  </wd-form>
</template>

<script setup>
import { useToast } from "wot-design-uni";
import { ref } from "vue";
import { request } from "../../utils/request";
import { getLoginCaptcha, login } from "../../api/auth";
const toast = useToast();
const model = ref({});
const form = ref({});
const captchaUrl = ref("");

const refreshCaptcha = () => {
  getLoginCaptcha(Date.now()).then((res) => {
    captchaUrl.value = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(
      res
    )}`;
  });
};

// 初始化时获取验证码
refreshCaptcha();

const handleSubmit = () => {
  form.value.validate().then(({ valid, errors }) => {
    if (!valid) return;
    login(model.value).then((res) => {
      uni.setStorageSync("token", res.data.token);
      uni.setStorageSync("user", res.data.user);
      toast.success("登录成功");
      setTimeout(() => {
        uni.switchTab({
          url: "/pages/personalCenter/personalCenter",
        });
      }, 1500);
    });
  });
};
const toRegister = () => {
  uni.redirectTo({
    url: "/pages/register/register",
  });
};
</script>

<style></style>
